<template>
  <div class="app-container">
    <el-form label-position="right" label-width="150px">
      <el-form-item label="店铺轮播图">
        <Upload
          typeName="deShopCarousel"
          :fileList="deShopCarousel"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
      /></el-form-item>

      <el-form-item label="产品分类首图">
        <Upload
          typeName="deProCategories"
          :fileList="deProCategories"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
      /></el-form-item>
      <el-form-item label="企业介绍首图">
        <Upload
          typeName="deCompanyProfileFirst"
          :fileList="deCompanyProfileFirst"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>

      <el-form-item label="个人中心首图">
        <Upload
          typeName="dePersonalCenter"
          :fileList="dePersonalCenter"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
      /></el-form-item>
      <el-form-item label="店铺LOGO正方形">
        <Upload
          typeName="deLogoSquare"
          :fileList="deLogoSquare"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
      /></el-form-item>

      <el-form-item label="店铺LOGO长条形">
        <Upload
          typeName="deLogoRectangle"
          :fileList="deLogoRectangle"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>
      <el-form-item label="企业宣传片">
        <Upload
          typeName="deCorporateVideo"
          :fileList="deCorporateVideo"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>
      <el-form-item label="店铺首页图片">
        <Upload
          typeName="deStoreHomePicture"
          :fileList="deStoreHomePicture"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>

      <el-form-item label="企业介绍图片">
        <Upload
          typeName="deCompanyProfile"
          :fileList="deCompanyProfile"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认提交</el-button>
      </el-form-item>
    </el-form>

    <Progress v-if="showProgress" :percentageNum="percentageNum" />
  </div>
</template>

<script>
import Upload from "@/components/upload";
import { getUploadKey, ossUpload, getFileList, delFile } from "@/api/upload";
export default {
  name: "Decoration",
  components: {
    Upload
  },
  data() {
    return {
      deShopCarousel: [],
      deProCategories: [],
      deCompanyProfileFirst: [],
      dePersonalCenter: [],
      deLogoSquare: [],
      deLogoRectangle: [],
      deCorporateVideo: [],
      deStoreHomePicture: [],
      deCompanyProfile: [],
      //上传文件数--------------------------------------------
      uploadFileNum: 0,
      //文件上传数--------------------------------------------
      uploadSuccessNum: 0,
      //初始化文件（曾经存在的文件）--------------------------------------------
      initFileList: [],
      // 需要删除的文件uuid
      delFileUuid: "",
      // 当前上传文件列表
      currentUploadList: [],
      //是否显示进度
      showProgress: false
    };
  },

  created() {
    this.getAllFile();
  },
  computed: {
    percentageNum() {
      let currentUpload = 0;
      let total = 0;
      this.currentUploadList.forEach(item => {
        currentUpload += item.loaded;
        total += item.total;
      });
      return ((currentUpload / total) * 100) | 0;
    }
  },
  methods: {
    validatorFn(file) {
      return true;
    },

    // 确定修改
    onSubmit() {
      // 上传文件
      this.addFile();
      // 删除文件
      this.removeFile();
    },

    // 获取全部文件
    getAllFile() {
      //查询文件--------------------------------------------
      const params = {
        page: 0,
        pageSize: 0,
        parentUuid: this.$store.getters.shopUuid
      };
      getFileList(params).then(res => {
        console.log("🚀 ~ file: index.vue ~ line 138 ~ getFileList ~ res", res);
        if (res.state == 100) {
          this.deShopCarousel = [];
          this.deProCategories = [];
          this.deCompanyProfileFirst = [];
          this.dePersonalCenter = [];
          this.deLogoSquare = [];
          this.deLogoRectangle = [];
          this.deCorporateVideo = [];
          this.deStoreHomePicture = [];
          this.deCompanyProfile = [];
          res.items.forEach(item => {
            switch (item.typeName) {
              case "deShopCarousel":
                this.deShopCarousel.push(item);
                break;
              case "deProCategories":
                this.deProCategories.push(item);
                break;
              case "deCompanyProfileFirst":
                this.deCompanyProfileFirst.push(item);
                break;
              case "dePersonalCenter":
                this.dePersonalCenter.push(item);
                break;
              case "deLogoSquare":
                this.deLogoSquare.push(item);
                break;
              case "deLogoRectangle":
                this.deLogoRectangle.push(item);
                break;
              case "deCorporateVideo":
                this.deCorporateVideo.push(item);
                break;
              case "deStoreHomePicture":
                this.deStoreHomePicture.push(item);
                break;
              case "deCompanyProfile":
                this.deCompanyProfile.push(item);
                break;
            }
          });
        }
      });
    },

    // 是否有需要上传的文件
    needUploadList() {
      return this.deShopCarousel
        .concat(this.deProCategories)
        .concat(this.deCompanyProfileFirst)
        .concat(this.dePersonalCenter)
        .concat(this.deLogoSquare)
        .concat(this.deLogoRectangle)
        .concat(this.deCorporateVideo)
        .concat(this.deStoreHomePicture)
        .concat(this.deCompanyProfile)
        .filter(item => item.raw);
    },

    // 上传文件
    addFile() {
      this.uploadSuccessNum = 0;
      this.uploadFileNum = 0;
      const shopData = {
        uuid: this.$store.getters.shopUuid,
        shopUuid: this.$store.getters.shopUuid
      };
      this.showProgress = true;
      this.currentUploadList = [];
      this.needUploadList().forEach((fileItem, index) => {
        this.currentUploadList.push({
          loaded: 0,
          total: 0
        });
        this.uploadFileNum += 1;
        this.getUploadKey(shopData, fileItem, index);
      });
    },

    //获取上传凭证--------------------------------------------
    async getUploadKey(shopData, fileItem, index) {
      const data = {
        fileName: fileItem.name,
        fileSize: fileItem.size,
        parentUuid: shopData.uuid,
        shopUuid: shopData.shopUuid,
        typeName: fileItem.typeName
      };
      const res = await getUploadKey(data);
      if (res.state == 100) {
        this.ossUpload(res.items, fileItem, index);
      }
    },

    //上传阿里云--------------------------------------------
    async ossUpload(key, fileItem, index) {
      const formData = new FormData();
      formData.append("policy", key.policy);
      formData.append("OSSAccessKeyId", key.accessid);
      formData.append("success_action_status", 200);
      formData.append("signature", key.signature);
      formData.append("key", key.dir);
      formData.append("file", fileItem.raw);
      const host = key.host;
      const res = await ossUpload(formData, host, this.uploadCallback, index);
      if (res.status === 200) {
        this.uploadSuccessNum += 1;
        if (this.uploadSuccessNum == this.uploadFileNum) {
          this.uploadSuccessNum = 0;
          this.uploadFileNum = 0;
          this.showProgress = false;
          this.$message({ type: "success", message: "修改成功" });
        }
      }
    },

    //上传回调--------------------------------------------
    uploadCallback(progress, index) {
      let uploadData = {
        loaded: progress.loaded,
        total: progress.total
      };
      this.currentUploadList.splice(index, 1, uploadData);
    },

    // 需要删除的文件
    needRemoveFile(file) {
      let uuid = file[0].uuid || null;
      if (uuid) {
        this.delFileUuid += uuid + ",";
      }
    },

    // 删除文件操作
    removeFile() {
      if (this.delFileUuid) {
        const params = {
          uuid: this.delFileUuid
        };
        delFile(params);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  max-width: 1080px;

  .contact-person {
    margin: 10px 0;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
